package com.jiechuang.user.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jiechuang.common.bean.User;
import com.jiechuang.common.bean.addOrUpdate.UserAddOrUpdate;
import com.jiechuang.common.exception.AddException;
import com.jiechuang.common.exception.DeleteException;
import com.jiechuang.common.exception.UpdateException;
import com.jiechuang.user.dto.UserQueryInfo;
import com.jiechuang.user.mapper.UserMapper;
import com.jiechuang.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public PageInfo<User> getUserList(UserQueryInfo userQueryInfo) {
        PageHelper.startPage(userQueryInfo.getPageNum(), userQueryInfo.getPageSize());
        List<User> userList = userMapper.getUserList(userQueryInfo);
        return new PageInfo<>(userList);
    }

    @Override
    public void addUser(UserAddOrUpdate userAddOrUpdate) {
        int i=userMapper.addUser(userAddOrUpdate);
        if(i==0){
            throw new AddException("新增失败");
        }
    }

    @Override
    public User getUser(Integer id) {
        return userMapper.getUser(id);
    }

    @Override
    public void updateUser(UserAddOrUpdate userAddOrUpdate) {
        int i=userMapper.updateUser(userAddOrUpdate);
        if(i==0){
            throw new UpdateException("修改失败");
        }
    }

    @Override
    public void deleteUser(Integer id) {
        int i=userMapper.deleteUser(id);
        if(i==0){
            throw new DeleteException("删除失败");
        }
    }

    @Override
    public void updateUserStatus(Integer id) {
        int i=userMapper.updateUserStatus(id);
        if(i==0){
            throw new UpdateException("修改失败");
        }
    }

    @Override
    public void giveRole(Integer userId, List<Integer> roleIds) {
        userMapper.deleteRolesByUserId(userId);
        if(!CollectionUtils.isEmpty(roleIds)){
            userMapper.batchAddRoleByUserId(userId,roleIds);
        }

    }
}
